﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using XieCan.AspMVC.Helpers;
using XieCan.AspMVC.ViewModels;

namespace XieCan.AspMVC.Web.Controllers
{
    [AllowAnonymous]
    public class AccountController : BaseController
    {
        public ActionResult Login()
        {
            return View();
        }

        public FileResult GetCode()
        {
            var code = VerifyCodeHelper.GetCodeZh(4);
            TempData["VerifyCode"] = code;
            return File(VerifyCodeHelper.CreateImageZh(code), "image/jpg");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel login, string ReturnUrl = "")
        {
            if (ModelState.IsValid)
            {
                if (TempData["VerifyCode"] == null)
                {
                    ModelState.AddModelError(nameof(login.Code), "请先获取验证码");
                }
                else if (login.Code != TempData["VerifyCode"].ToString())
                {
                    ModelState.AddModelError(nameof(login.Code), "验证码不正确，请重新获取");
                }
                else
                {
                    var res = OperateResult<LoginViewModel>.Succeeded(login); //AccountBLL.Login(login);
                    if (!res.Success)
                    {
                        FormsAuthentication.SignOut();
                        Response.Cookies[FormsAuthentication.FormsCookieName].Expires.AddDays(-1);
                        ModelState.AddModelError(res.Key, res.Message);
                    }
                    else
                    {
                        // 创建登录票据
                        DateTime now = DateTime.Now;
                        DateTime end = now.AddDays(14);

                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                            1,                          // 版本号
                            login.Account,              // 姓名
                            now,                    // 颁发时间
                            end,                 // 到期时间
                            false,                      // 跨浏览器访问
                            login.Account               // 自定义用户数据
                            );

                        // 加密票据
                        string token = FormsAuthentication.Encrypt(ticket);
                        // 保存票据
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName)
                        {
                            HttpOnly = true,
                            Expires = end,
                            Value = token
                        };
                        Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
                        Response.Cookies.Set(cookie);

                        //FormsAuthentication.SetAuthCookie(login.Account, true);

                        if (string.IsNullOrWhiteSpace(ReturnUrl))
                        {
                            return RedirectToAction("Index", "Admin");
                        }
                        else
                        {
                            return Redirect(ReturnUrl);
                        }
                    }
                }
            }
            return View();
        }

        public void Logout()
        {
            FormsAuthentication.SignOut();
            Response.Cookies[FormsAuthentication.FormsCookieName].Expires.AddDays(-1);
            FormsAuthentication.RedirectToLoginPage();
        }
    }
}